/*
 * @Date: 2022-04-19 23:16:49
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2022-05-10 11:24:50
 * @FilePath: \go-gethttp\main.go
 */
package main

import (
	"bytes"
	"go-gethttp/colorwinconsole"
	"go-gethttp/config"
	"go-gethttp/log"
	"io"
	"io/ioutil"
	"net/http"
	"sync"
	"time"
)

// 发送GET请求
// url：         请求地址
// response：    请求返回的内容
func Get(url string) string {
	// 超时时间：5秒
	client := &http.Client{Timeout: 60 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		log.Write(log.Error, err.Error())
		return err.Error()
	}
	defer resp.Body.Close()

	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			log.Write(log.Error, err.Error())
			return err.Error()
		}
	}
	log.Write(log.Info, result.String())
	return result.String()
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func Post(url string, data string, contentType string) string {

	// 超时时间：60秒
	client := &http.Client{Timeout: 60 * time.Second}
	resp, err := client.Post(url, contentType, bytes.NewBuffer([]byte(data)))
	if err != nil {
		log.Write(log.Error, err.Error())
		return err.Error()
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	log.Write(log.Info, string(result))
	return string(result)
}

func main() {

	var wg sync.WaitGroup
	wg.Add(len(config.Instance().Request))

	//遍历map
	for _, v := range config.Instance().Request {
		go run(v)
	}
	colorwinconsole.ColorPrint(`欢迎使用简洁服务请求工具`, `https://gitee.com/chun22222222`)
	wg.Wait()

}

func run(v config.RequestConf) {

	if v.Method == "GET" {

		for {
			Get(v.Url)
			time.Sleep(time.Duration(v.Interval) * time.Second)
		}

	} else {
		for {
			Post(v.Url, v.Data, "application/json")
			time.Sleep(time.Duration(v.Interval) * time.Second)
		}

	}

}
